package controllers;

import java.awt.event.ActionEvent;
import java.util.Vector;

import dialogs.DeleteTupleDialog;
import dialogs.InsertTupleDialog;

import models.StoredModel;
import system.View;

public class StoredController extends AbstractMenuItemController {
	private StoredModel stored = new StoredModel();

	public StoredController(View v) {
		super(v);
		abstractModel = stored;
		stored.addExceptionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String actionCommand = e.getActionCommand();

		if (actionCommand.equals("Remove Item from Store"))
			showDialogWindow(new DeleteTupleDialog(view, actionCommand, "Key",
					new String[] { "Store Name: ", "Item UPC: " }, this));
		else if (actionCommand.equals("Add Item to Store"))
			showDialogWindow(new InsertTupleDialog(view, actionCommand,
					"Item/Store", new String[] { "Store Name: ", "Item UPC: ",
							"Quantity in Stock: ", }, this));
	}

	@Override
	public int validateInsert(Vector<String> s) {
		if (s.size() != 3)
			return VALIDATIONERROR;

		try {
			String sname;
			int upc;
			int stock;
			if (s.get(0).trim().length() != 0)
				sname = s.get(0).trim();
			else return VALIDATIONERROR;
			if (s.get(1).length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;
			if (s.get(2).length() != 0)
				stock = Integer.valueOf(s.get(2).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Inserting Item to Store...");

			if (stored.insert(sname, upc, stock)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}

	@Override
	public int validateDelete(Vector<String> s) {
		if (s.size() != 2)
			return VALIDATIONERROR;

		try {
			Integer upc;
			String sname;

			if (s.get(0).trim().length() != 0)
				sname = s.get(0).trim();
			else return VALIDATIONERROR;
			if (s.get(1).trim().length() != 0)
				upc = Integer.valueOf(s.get(1).trim());
			else return VALIDATIONERROR;

			view.updateStatusBar("Deleting Item from Store...");

			if (stored.delete(sname, upc)) return operationSuccess();
			else return operationFailure();
		} catch (NumberFormatException ex) {
			return VALIDATIONERROR;
		}
	}
}